<template>
  <div class="dashboard-container">
    <el-container class="main-container">
      <el-aside width="220px">
        <div class="sidebar">
          <div class="logo-container">
            <h2>KG</h2>
          </div>
          <el-menu 
            :default-active="activeMenu" 
            class="sidebar-menu"
            router
          >
            <el-menu-item index="/dashboard">
              <el-icon><el-icon-home /></el-icon>
              <span>仪表盘</span>
            </el-menu-item>
            <el-menu-item index="/dashboard/reports">
              <el-icon><el-icon-document /></el-icon>
              <span>报告上传和管理</span>
            </el-menu-item>
            <el-menu-item index="/dashboard/graph">
              <el-icon><el-icon-connection /></el-icon>
              <span>图谱展示</span>
            </el-menu-item>
            <el-menu-item index="/dashboard/extract">
              <el-icon><ElIconNotebook /></el-icon>
              <span>信息抽取</span>
            </el-menu-item>
            <el-menu-item index="/dashboard/trust">
              <el-icon><el-icon-checked /></el-icon>
              <span>图谱可信度评估</span>
            </el-menu-item>
            <el-menu-item index="/dashboard/models">
              <el-icon><ElIconSetting /></el-icon>
              <span>模型管理</span>
            </el-menu-item>
           
          </el-menu>
        </div>
      </el-aside>
      <el-container>
        <el-header height="60px">
          <div class="header-content">
            <div class="header-title">
              <h2>{{ pageTitle }}</h2>
            </div>
            <div class="user-info">
              <el-dropdown trigger="click">
                <span class="user-dropdown">
                  {{ user?.username }}
                  <el-icon class="el-icon--right"><el-icon-arrow-down /></el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="handleLogout">退出登录</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
        </el-header>
        <el-main>
          <router-view v-if="isAuthenticated" :threat-intel-count="threatIntelCount" :entity-node-count="entityNodeCount" :relationship-count="relationshipCount" :loading="loading" />
          <div v-else class="loading-container">加载中...</div>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, provide } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useAuthStore } from '../stores/auth'
import { storeToRefs } from 'pinia'
import { ElMessage } from 'element-plus'
import { 
  HomeFilled as ElIconHome,
  Connection as ElIconConnection,
  CircleCheckFilled as ElIconChecked,
  Document as ElIconDocument,
  ArrowDown as ElIconArrowDown,
  Notebook as ElIconNotebook,
  Setting as ElIconSetting
} from '@element-plus/icons-vue'
import axios from 'axios'

const router = useRouter()
const route = useRoute()
const authStore = useAuthStore()
const { user, isAuthenticated } = storeToRefs(authStore)

const activeMenu = computed(() => route.path)

const pageTitle = computed(() => {
  switch (route.path) {
    case '/dashboard':
      return '仪表盘'
    case '/dashboard/graph':
      return '知识图谱'
    case '/dashboard/reports':
      return '报告上传和管理'
    case '/dashboard/trust':
      return '可信度评估'
    case '/dashboard/models':
      return '模型管理'
    default:
      return '威胁情报图谱构建和可信度评估系统'
  }
})

// 添加统计数据状态
const threatIntelCount = ref('加载中...')
const entityNodeCount = ref('加载中...')
const relationshipCount = ref('加载中...')
const loading = ref(true)

// 提供统计数据给子组件
provide('dashboardStats', {
  threatIntelCount,
  entityNodeCount,
  relationshipCount,
  loading
})

// 获取统计数据
const fetchStatistics = async () => {
  loading.value = true
  try {
    // 这里使用API获取统计数据
    // 注意：替换下面的URL为实际的API端点
    const response = await axios.get('/api/statistics', {
      headers: {
        Authorization: `Bearer ${localStorage.getItem('token')}`
      }
    })
    
    // 如果API调用成功，更新统计数据
    threatIntelCount.value = response.data.threatIntelCount || 0
    entityNodeCount.value = response.data.entityNodeCount || 0
    relationshipCount.value = response.data.relationshipCount || 0
  } catch (error) {
    console.error('获取统计数据失败:', error)
    
    // 如果主API不可用，尝试使用备用API
    try {
      // 获取知识图谱数据
      const graphResponse = await axios.get('http://localhost:8000/graph', {
        headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
      })
      
      // 获取威胁情报数据
      const intelResponse = await axios.get('http://localhost:8000/intel', {
        headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
      })
      
      threatIntelCount.value = intelResponse.data.length
      entityNodeCount.value = graphResponse.data.nodes.length
      relationshipCount.value = graphResponse.data.links.length
    } catch (backupError) {
      console.error('备用数据获取失败:', backupError)
      // 如果API调用失败，使用模拟数据
      threatIntelCount.value = '125'
      entityNodeCount.value = '347'
      relationshipCount.value = '512'
      ElMessage.warning('统计数据加载失败，显示示例数据')
    }
  } finally {
    loading.value = false
  }
}

onMounted(async () => {
  try {
    if (!user.value) {
      await authStore.fetchUser()
    }
    // 加载统计数据
    fetchStatistics()
  } catch (error) {
    ElMessage.error('获取用户信息失败')
    authStore.logout()
    router.push('/login')
  }
})

const handleLogout = () => {
  authStore.logout()
  router.push('/login')
  ElMessage.success('已退出登录')
}
</script>

<style scoped>
.dashboard-container {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.main-container {
  height: 100vh;
}

.sidebar {
  height: 100%;
  background-color: #304156;
  color: white;
}

.logo-container {
  height: 60px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #263445;
}

.logo-container h2 {
  color: white;
  margin: 0;
  font-size: 26px;
}

.sidebar-menu {
  border-right: none;
  background-color: #304156;
}

:deep(.el-menu) {
  background-color: #304156;
}

:deep(.el-menu-item) {
  color: #bfcbd9;
}

:deep(.el-menu-item.is-active) {
  color: #409eff;
  background-color: #263445;
}

.el-header {
  background-color: white;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  padding: 0 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
}

.header-title h2 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-dropdown {
  cursor: pointer;
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #606266;
}

.el-main {
  padding: 20px;
  background-color: #f5f7fa;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  font-size: 16px;
  color: #909399;
}
</style> 